const express = require('express')
const app = express()
// var multipart = require('connect-multiparty');
var net = require('net');
var fs = require('fs');
var http = require('http');
var https = require('https');
var privateKey = fs.readFileSync('./ssl/privatekey.pem', 'utf8');
var certificate = fs.readFileSync('./ssl/certificate.pem', 'utf8');
// var credentials = { key: privateKey, cert: certificate };

// var httpServer = http.createServer(app);
// var httpsServer = https.createServer(credentials, app);
// var PORT = 8082;
// var SSLPORT = 8081;
var basePort = 8081
var httpPort = 8082;
var httpsPort = 8083;
var server = http.createServer(app).listen(httpPort);
const httpsOption = {
    key: fs.readFileSync('./ssl/privatekey.pem', 'utf8'),
    cert: fs.readFileSync('./ssl/certificate.pem', 'utf8')
}

var sserver = https.createServer(httpsOption, app).listen(httpsPort);

net.createServer(function (socket) {
    socket.once('data', function (buf) {
        console.log(buf[0]);
        // https数据流的第一位是十六进制“16”，转换成十进制就是22
        var address = buf[0] === 22 ? httpsPort : httpPort;
        //创建一个指向https或http服务器的链接
        var proxy = net.createConnection(address, function () {
            proxy.write(buf);
            //反向代理的过程，tcp接受的数据交给代理链接，代理链接服务器端返回数据交由socket返回给客户端
            socket.pipe(proxy).pipe(socket);
        })

        proxy.on('error', function (err) {
            console.log(err)
        })
    })

    socket.on('error', function (err) {
        console.log(err);
    })
}).listen(basePort, () => {
    console.log('Server is running on %s', basePort);
});


/**
 * 解析body
 */

//导入解析表单数据的中间件body-parser
var bodyParser = require('body-parser')
//使用app.use()来注册中间件
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

/**
 * 解决跨域
 */

//导入cors中间件
const cors = require('cors')
app.use(cors())
// app.use(express.json());

var vertoken = require('./utils/token/token')


/**
 * token认证
 */

// 取jwt的密钥
const config = require('./config')
const jwtSecretKey = config.jwtSecretKey

// 解析 token 的中间件
const expressJwt = require('express-jwt')

app.use(express.static("./public"));//将静态资源托管，这样才能在浏览器上直接访问预览图片或则html页面
// //验证token是否过期并规定那些路由不需要验证
// app.use(expressJwt({
//     secret: jwtSecretKey,
//     algorithms: ['HS256']
// }).unless({
//     //用户第一次登录的时候不需要验证token
//     path: ['/api/admin/login', '/api/client/**']  //不需要验证的接口名称
// }))
// 验证token是否过期并规定那些路由不需要验证
app.use(["/api/admin"], expressJwt({
    secret: jwtSecretKey,
    algorithms: ['HS256']
}).unless({
    path: ['/api/admin/login', '/login']  //不需要验证的接口名称
}))

//解析token获取用户信息
app.use(function (req, res, next) {
    //注意此处token；authorization设置要与设置一致否则可能出现token为空
    token = req.headers['authorization'];
    // const token = req.headers['authorization'].replace("Bearer ", "");
    // console.log('token====>', token)
    if (token == undefined) {
        return next();
    } else {
        vertoken.getToken(token).then((data) => {
            // console.log('data===>', data)
            req.data = data;             //解析成功后返回设置基本信息（通过req.data判断是否过期）
            return next();
        }).catch((error) => {
            return next();
        })
    }
});

//token失效返回信息
app.use(function (err, req, res, next) {
    // console.log('验证token')
    if (err.status == 401) {
        console.log('token失效，请重新登录！')
        return res.json({
            code: 401,
            msg: 'token失效',
            data: {}
        })
        //可以设置返回json 形式  res.json({message:'token失效'})
    }
    return next();
})

/**
 * 创建管理端接口
 */

//导入并使用管理员路由模块
const adminRouter = require('./router/admin/admin')
app.use('/api', adminRouter)
//导入并使用学习资料路由模块
const studyDataRouter = require('./router/admin/studyData')
app.use('/api', studyDataRouter)
//导入并使用学习视频路由模块
const studyVideosRouter = require('./router/admin/studyVideos')
app.use('/api', studyVideosRouter)
//导入并使用公告路由模块
const noticeRouter = require('./router/admin/notice')
app.use('/api', noticeRouter)
//导入并使用事件路由模块
const eventRouter = require('./router/admin/event')
app.use('/api', eventRouter)
//导入并使用申请路由模块
const applicationRouter = require('./router/admin/application')
app.use('/api', applicationRouter)

//导入并使用文件上传路由模块
const uploadRouter = require('./router/admin/upload')
app.use('/api', uploadRouter)

//导入成员路由模块
const memberRouter = require('./router/admin/member')
app.use('/api', memberRouter)

//导入学生路由模块
const studentRouter = require('./router/admin/student')
app.use('/api', studentRouter)

//导入简介路由模块
const descriptionRouter = require('./router/admin/description')
app.use('/api', descriptionRouter)

//导入图标路由模块
const tagsIconRouter = require('./router/admin/tagsIcon')
app.use('/api', tagsIconRouter)

/**
 * 创建用户端接口
 */

//导入并使用学习资料路由模块
const clientStudyDataRouter = require('./router/client/studyData')
app.use('/api', clientStudyDataRouter)
//导入并使用学习视频路由模块
const clientStudyVideosRouter = require('./router/client/studyVideos')
app.use('/api', clientStudyVideosRouter)
//导入并使用公告路由模块
const clientNoticeRouter = require('./router/client/notice')
app.use('/api', clientNoticeRouter)
//导入并使用事件路由模块
const clientEventRouter = require('./router/client/event')
app.use('/api', clientEventRouter)
//导入并使用申请路由模块
const clientApplicationRouter = require('./router/client/application')
app.use('/api', clientApplicationRouter)

//导入并使用申请路由模块
const clientTagsRouter = require('./router/client/tags')
app.use('/api', clientTagsRouter)

//导入并使用历史记录路由模块
const videoHistory = require('./router/client/videoHistory')
app.use('/api', videoHistory)

//导入并使用表单路由模块
const formRouter = require('./router/client/form')
app.use('/api', formRouter)

//导入并使用表单路由模块
const descriptionClientRouter = require('./router/client/description')
app.use('/api', descriptionClientRouter)

// Welcome
app.get('/', function (req, res) {
    if (req.protocol === 'https') {
        res.status(200).send('Welcome to Safety Land!');
    }
    else {
        res.status(200).send('Welcome!');
    }
});

/**
 * 开启监听端口
 */
// httpServer.listen(PORT, function () {
//     console.log('HTTP Server is running on: http://localhost:%s', PORT);
// });
// httpsServer.listen(SSLPORT, function () {
//     console.log('HTTPS Server is running on: https://localhost:%s', SSLPORT);
// });